package com.css.chat.ui.controller;

import com.css.chat.base.UiBaseService;
import com.css.chat.logic.chat.ChatManager;
import com.css.chat.logic.chat.SendImg;
import com.css.chat.logic.chat.SendVideoImg;
import com.css.chat.logic.user.UserManager;
import com.css.chat.ui.ControlledStage;
import com.css.chat.ui.R;
import com.css.chat.ui.StageController;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.image.Image;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.OpenCVFrameConverter;
import org.bytedeco.javacv.OpenCVFrameGrabber;
import org.bytedeco.opencv.opencv_core.IplImage;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.WritableRaster;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;

public class ChatToPointController implements ControlledStage {

	@FXML
	private Label userIdUi;

	@FXML
	private TextArea msgInput;

	@FXML
	private ScrollPane outputMsgUi;

	OpenCVFrameGrabber grabber = null;

	@FXML
	private void sendMessage() throws IOException {
		final long userId = Long.parseLong(userIdUi.getText());
		String message = msgInput.getText();

		System.out.println("----send message---" + message);

		ChatManager.getInstance().sendMessageTo(userId, message);
	}


	@Override
	public Stage getMyStage() {
		StageController stageController = UiBaseService.INSTANCE.getStageController();
		return stageController.getStageBy(R.id.ChatToPoint);
	}

	@FXML
	private void close() {
		UiBaseService.INSTANCE.getStageController().closeStage(R.id.ChatToPoint);
	}

	@FXML
	private void choseImg(){
		final long userId = Long.parseLong(userIdUi.getText());
		/**获取图片*/
		FileChooser fileChooser = new FileChooser();
		fileChooser.setTitle("Open Resource File");
		fileChooser.getExtensionFilters().addAll(
				new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif"));
		StageController stageController = UiBaseService.INSTANCE.getStageController();
		Stage stage = stageController.getStageBy(R.id.FileShow);
		File choseFile = fileChooser.showOpenDialog(stage.getScene().getWindow());

		Image image = new Image(choseFile.toURI().toString());
		SendImg sendFile = SendImg.getInstance();

		/**展示图片*/
		sendFile.receiveFriendPrivateMessage(UserManager.getInstance().getMyUserId(), image);
		/**发送图片*/
		sendFile.sendImgTo(userId, choseFile);

		/**发送图片*/
		System.out.println(choseFile);
	}

	@FXML
	private void choseFile(){

	}

	@FXML
	private void choseVideo(){

		final long userId = Long.parseLong(userIdUi.getText());
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					startVideo();
					while(true) {
						Frame frame = grabber.grab();

						/**Frame转图片byte*/
						OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();
						IplImage image = converter.convert(frame);
						BufferedImage bufferedImage = new BufferedImage(image.width(),
								image.height(), BufferedImage.TYPE_3BYTE_BGR);
						WritableRaster raster = bufferedImage.getRaster();
						DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();
						byte[] data = dataBuffer.getData();
						((ByteBuffer) image.createBuffer()).get(data);
						ByteArrayOutputStream out = new ByteArrayOutputStream();
						ImageIO.write(bufferedImage, "jpg", out);
						byte[] bytes =  out.toByteArray();

						SendVideoImg.getInstance().sendVideoImgTo(userId, bytes, 1);
						Thread.sleep(10);//50毫秒刷新一次图像
					}
				}catch (Exception e){
					e.printStackTrace();
				}
			}
		}).start();


	}

	@FXML
	private void closeVideo(){
		final long userId = Long.parseLong(userIdUi.getText());
		stopVideo();
		SendVideoImg.getInstance().sendVideoImgTo(userId, "关闭".getBytes(), 0);
	}

	public void startVideo(){
		try {
			grabber = new OpenCVFrameGrabber(0);
			grabber.start();   //开始获取摄像头数据
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void stopVideo(){
		try {
			grabber.stop();
		} catch (FrameGrabber.Exception e) {
			e.printStackTrace();
		}
	}


}


